package com.yuji.aacar.widgets.countdownbutton;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import com.yuji.aacar.R;

import java.util.Observable;
import java.util.Observer;


/**
 * <li>Package: {@link WCountDownButton}
 * <li>Author: cyh
 * <li>Date: 2017/6/19 14:59
 * <li>Discription: 倒计时按钮
 */

public class WCountDownButton extends android.support.v7.widget.AppCompatButton implements Observer {
    private long millisInFuture;//倒计时总时间
    private long countDownInterval;//倒计时间隔时间
    private String countDownBeforeText;//未开始倒计时的文案显示
    private String countDownText;//倒计时过程中的文案显示

    private CountDownHelper countDownHelper;//倒计时帮助类

    public WCountDownButton(Context context) {
        super(context);
        init(null);
    }

    public WCountDownButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public WCountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.WCountDownButton);
            millisInFuture = array.getInt(R.styleable.WCountDownButton_cdb_millisInFuture, 60000);
            countDownInterval = array.getInt(R.styleable.WCountDownButton_cdb_countDownInterval, 1000);
            countDownBeforeText = array.getString(R.styleable.WCountDownButton_cdb_countDownBeforeText);
            countDownText = array.getString(R.styleable.WCountDownButton_cdb_countDownText);
            array.recycle();
        }

        //初始化倒计时帮助类
        countDownHelper = CountDownHelper.getInstance(millisInFuture, countDownInterval);
        countDownHelper.addObserable(this);

        setText(countDownBeforeText);
    }

    @Override
    public void update(Observable observable, Object o) {
        long time = Long.parseLong(o.toString()) / 1000;
        if (time <= 0) {//倒计时结束
            setText(countDownBeforeText);
            setEnabled(true);
        } else {//正在倒计时
            setText( time + " s");
            setEnabled(false);
        }
    }

    /**
     * 开始倒计时
     */
    public void startCountDown() {
        countDownHelper.addObserable(this);//绑定观察者
        countDownHelper.startCountDown();
    }
}
